import 'package:adaptive_dialog/adaptive_dialog.dart';

import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

Map<Permission, String> permissionTextMap = {
  Permission.camera: '相机',
  Permission.storage: '存储',
  Permission.photos: '相册',
  Permission.microphone: '麦克风',
};

/// 权限申请
class PermissionUtil {
  static Future<Map<Permission, PermissionStatus>> reqPermissions({
    List<Permission> permissions = const [],
    bool displayRationale = true,
    void Function(Map<Permission, PermissionStatus>)? onPermissionRequestResult,
  }) async {
    if (permissions.isEmpty) {
      permissions = [Permission.camera]; // 默认请求相机权限
    }

    Map<Permission, PermissionStatus> statuses = await permissions.request();

    // 处理拒绝或失败的权限
    if (displayRationale) {
      statuses.forEach((Permission permission, PermissionStatus status) {
        // 永久拒绝或家长设置
        if (status.isPermanentlyDenied || status.isRestricted) {
          showRationaleDialog(permission);
        }
      });
    }

    // 回调函数形式返回结果
    if (onPermissionRequestResult != null) {
      onPermissionRequestResult(statuses);
    }

    return statuses;
  }

  static Future<void> showRationaleDialog(Permission permission) async {
    final OkCancelResult res = await showOkCancelAlertDialog(
      context: Get.context!,
      title: '提示',
      message: '请打开[设置]手动开启${permissionTextMap[permission] ?? ''}权限',
      okLabel: '打开',
      cancelLabel: '取消',
      style: AdaptiveStyle.iOS,
    );
    if (res == OkCancelResult.ok) {
      openAppSettings();
    } else if (res == OkCancelResult.cancel) {
      Get.back();
    }
  }
}
